﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace MediaRecommender.Model
{
    //Collection class for users
    public sealed class UserCollection : IEnumerable
    {
        private static readonly UserCollection _instance = new UserCollection();
        private List<User> _database;
        private String FilePath = "c:\\P3Project log folder\\"; // AppDomain.CurrentDomain.BaseDirectory + "\\Db\\";
        private string Filename = "UserCollection.txt";

        private UserCollection()
        {
            _database = new List<User>();
        }

        public static UserCollection Instance
        {
            get { return _instance; }
        }

        public bool Add(User user)
        {
            if (!this.ContainsUser(user))
            {
                _database.Add(user);
                return true;
            }
            return false;
        }

        public bool Remove(User user)
        {
            return _database.Remove(user);
        }

        public bool ContainsUser(User user)
        {
            return _database.Contains(user);
        }

        public int CountUsers()
        {
            return _database.Count();
        }

        public User GetUser(string name)
        {
            return _database.Find(x => x.Name.Equals(name));
        }

        public User GetUser()
        {
            var user = _database[0];

            return user;
        }

        public List<User> GetAllDifferentUsers(string name)
        {
            return _database.Where(x => x.Name != name).ToList();
        }

        public List<User> GetAllUsers()
        {
            return _database;
        }

        public void WriteDbToFile()
        {
            ObjectToFile serializer = new ObjectToFile();
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }

            serializer.SerializeObject<List<User>>(FilePath + Filename, _database);
        }

        public void ReadDbFromFile()
        {
            ObjectToFile serializer = new ObjectToFile();

            if (Directory.Exists(FilePath))
            {
                try
                {
                    _database = serializer.DeSerializeObject<List<User>>(FilePath + Filename);
                }
                catch (FileNotFoundException)
                {
                }
            }
        }

        public IEnumerator GetEnumerator()
        {
            return _database.GetEnumerator();
        }
    }
}